<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="设备码" prop="IMEI">
                <el-input v-model="queryParams.IMEI" placeholder="请输入设备码" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="deviceState">
                <el-select v-model="queryParams.deviceState" placeholder="设备状态" clearable>
                    <el-option v-for="dict in deviceStateList" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="是否绑定" prop="isBound">
                <el-select v-model="queryParams.isBound" placeholder="是否绑定" clearable>
                    <el-option v-for="dict in boundList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="设备编号" align="center" prop="deviceId" /> -->
            <el-table-column label="设备imei" align="center" prop="imei" />
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="设备地址" align="center" prop="deviceAddr" />
            <!-- <el-table-column label="状态" align="center" prop="deviceState">
                <template slot-scope="scope">
                    {{ deviceStateMap[scope.row.deviceState] }}
                </template>
</el-table-column> -->
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view"
                        @click="handleView(scope.row, scope.index)">详细</el-button>
                    <el-button size="mini" type="text" icon="el-icon-date"
                        @click="handleViewLog(scope.row, scope.index)">日志</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改设备对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="设备imei" prop="imei">
                    <el-input v-model="form.imei" :disabled="form.deviceId ? true : false" placeholder="请输入设备码" />
                </el-form-item>
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备地址" prop="deviceAddr">
                    <el-input v-model="form.deviceAddr" placeholder="请输入设备地址" />
                </el-form-item>
                <!-- <el-form-item label="设备顺序" prop="postSort">
                    <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="设备状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                            dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 操作日志详细 -->
        <el-dialog title="设备详细" :visible.sync="openDetail" width="80%" append-to-body>
            <el-form ref="form" :model="form" label-width="100px" size="mini">
                <el-row>
                    <el-row type="flex">
                        <el-form-item style="width: 20%;" label="设备名称：">{{ form.deviceName }} </el-form-item>
                        <el-form-item style="width: 20%;" label="设备地址：">{{ form.deviceAddr }} </el-form-item>
                        <el-form-item style="width: 20%;" label="设备imei：">{{ form.imei }}</el-form-item>
                        <!-- <el-form-item style="width: 20%;" label="设备ID：">{{ form.deviceId }}</el-form-item> -->
                        <!-- <el-form-item style="width: 20%;" label="设备状态：">{{ deviceStateMap[form.deviceState]
                            }}</el-form-item> -->
                    </el-row>
                    <el-row type="flex">
                        <el-form-item style="width: 20%;" label="创建时间：">{{ form.createTime }}</el-form-item>
                        <el-form-item label="备注：">{{ form.remark }}</el-form-item>
                    </el-row>
                </el-row>
                <el-row class="alarm-log" v-if="form.deviceParameterLogList && form.deviceParameterLogList.length">
                    <template>
                        <template v-for="entry in form.deviceParameterLogList">
                            <template v-if="entry.name != 'cmd'">
                                <div class="log-item" :key="entry.key">
                                    <div class="log-key-block">
                                        <span class="log-name">{{ entry.name }}</span>
                                        <span class="log-subkey">{{ entry.key }}</span>
                                    </div>
                                    <span class="log-value">{{ entry.value }}</span>
                                </div>
                            </template>
                        </template>

                    </template>
                </el-row>
                <template v-else>
                    {{ form.deviceParameterLog }}
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="openDetail = false">关 闭</el-button>
            </div>
        </el-dialog>
        <!-- 设备日志 -->
        <LogDialog ref="logDialog" activeName="1"></LogDialog>
    </div>
</template>

<script>
import {
    deviceListApi, deviceDetailApi, deleteDeviceApi, addDeviceApi, updateDeviceApi, cancelDeviceApi,
    deviceInfoApi
} from "@/api/index";
import LogDialog from "./LogDialog";
import { parseJSONSafe } from '@/utils/jsonUtil';
import uploadJson from '@/components/LogDialog/upload.json';
export default {
    name: "Post",
    dicts: ['sys_normal_disable'],
    components: { LogDialog },
    data() {
        return {
            openDetail: false,//设备详情弹窗
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 设备表格数据
            postList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                IMEI: undefined,
                deviceName: undefined,
                deviceState: undefined,
                isBound: undefined,
                orderByColumn: "create_time",
                isAsc: "desc"
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                deviceName: [
                    { required: true, message: "设备名称不能为空", trigger: "blur" }
                ],
                deviceAddr: [
                    { required: true, message: "设备地址不能为空", trigger: "blur" }
                ],
                imei: [
                    { required: true, message: "设备imei不能为空", trigger: "blur" }
                ]
            },
            deviceStateList: [
                { label: "离线", value: 0 },
                { label: "在线", value: 1 },
                { label: "缺水", value: 2 },
                { label: "异常", value: 3 }
            ],
            boundList: [
                { label: "未绑定", value: 0 },
                { label: "已绑定", value: 1 },
                { label: "已注销", value: 2 }
            ],
            deviceInfoList: [],
            deviceStateMap: {
                0: "离线",
                1: "在线",
                2: "缺水",
                3: "异常"
            },
        }
    },
    created() {
        this.getList();

    },
    methods: {
        /** 查询设备绑定状态 */
        async deviceInfo() {
            deviceInfoApi().then(res => {
                // console.log(res, 'res-设备绑定状态');
                this.deviceInfoList = res.data;
            })
        },
        // 操作日志类型字典翻译
        typeFormat(row, column) {
            return this.selectDictLabel(this.dict.type.sys_oper_type, row.businessType)
        },
        // 日志详情
        handleViewLog(row) {
            this.$refs.logDialog.open(row.deviceId);
        },
        /** 详细按钮操作 */
        async handleView(row) {
            const res = await deviceDetailApi(row.deviceId);
            console.log(res, 'res-详细');
            if (res.code === 200) {
                if (res.data) {
                    // 解析原始日志字段为对象（如果可能）
                    if (res.data.deviceParameterLog) {
                        const parsed = parseJSONSafe(res.data.deviceParameterLog)
                        // console.log(parsed, '✅ 转成真正JSON对象')
                        res.data.deviceParameterLogJson = parsed || res.data.deviceParameterLog

                        // 把对象转换为数组并加上 name（从 uploadJson 映射），方便前端展示
                        if (typeof res.data.deviceParameterLogJson !== 'object' || !res.data.deviceParameterLogJson) {
                            res.data.deviceParameterLogList = []
                        } else {
                            try {
                                const obj = res.data.deviceParameterLogJson
                                res.data.deviceParameterLogList = Object.keys(obj).map(key => ({
                                    key,
                                    value: obj[key],
                                    // upload.json 的结构是 { key: { name: 'xxx', key: 'key' } }
                                    name: uploadJson && uploadJson[key] && uploadJson[key].name ? uploadJson[key].name : key
                                }))
                            } catch (e) {
                                res.data.deviceParameterLogList = []
                            }
                        }
                        console.log(res.data.deviceParameterLogList, '历史参数');
                    }
                }
                this.form = res.data;
                this.openDetail = true
            }
        },
        /** 查询设备列表 */
        getList() {
            this.loading = true
            deviceListApi(this.queryParams).then(response => {
                this.postList = response.rows
                this.total = response.total
                this.loading = false;
                this.deviceInfo();
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                postId: undefined,
                postCode: undefined,
                deviceName: undefined,
                postSort: 0,
                status: "0",
                remark: undefined
            }
            this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.deviceId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = "添加设备"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const deviceId = row.deviceId || this.ids
            deviceDetailApi(deviceId).then(response => {
                this.form = response.data
                this.open = true
                this.title = "修改设备"
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.deviceId != undefined) {
                        updateDeviceApi(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addDeviceApi(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功")
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const postIds = row.deviceId || this.ids
            this.$modal.confirm('是否确认删除设备编号为"' + postIds + '"的数据项？').then(function () {
                return deleteDeviceApi(postIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => { })
        },
        // 注销设备
        handleCancel(row) {
            const deviceId = row.deviceId || this.ids
            this.$modal.confirm('是否确认注销设备编号为"' + deviceId + '"的数据项？').then(function () {
                return cancelDeviceApi({ deviceId: deviceId })
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("注销成功")
            }).catch(() => { })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/post/export', {
                ...this.queryParams
            }, `post_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
<style lang="scss" scoped>
.like {
    cursor: pointer;
    font-size: 25px;
    display: inline-block;
}

.alarm-log {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    background: #fafafa;
    border-radius: 8px;
    padding: 8px 12px;
    // max-height: 500px;
    overflow-y: auto;
    font-size: 13px;
    line-height: 1.6;
    width: 100%;
    // border: 1px solid #000;
}

.log-item {
    background: #f7f8fa;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 6px 12px;
    min-width: 140px;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    color: #333;
    transition: all 0.3s;
    margin: 0 0px 10px 0;

}


.log-key {
    color: #666;
}

.log-key-block {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.log-name {
    color: #666;
}

.log-subkey {
    font-size: 11px;
    color: #999;
    margin-top: 2px;
}

.log-value {
    font-weight: 600;
    color: #333;
}

.log-alert {
    border-color: #f56c6c;
    background-color: #fff0f0;
    color: #d7282f;
}
</style>
